import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from '../../request/axios';

interface EvaluateItem {
    nickName: string;
    headPic: string;
    content: string;
    commentTime: number;
}

interface EvaluateState {
    list: EvaluateItem[];
    page: number;
    finished: boolean;
    loading: boolean;
    error: string | null;
}

const initialState: EvaluateState = {
    list: [],
    page: 1,
    finished: false,
    loading: false,
    error: null,
};

export const fetchEvaluates = createAsyncThunk(
    'evaluate/fetchList',
    async ({ doctorId, page, isRefresh = false }: { doctorId: string; page: number; isRefresh?: boolean }, { rejectWithValue }) => {
        try {
            const res = await axios.get('/health/user/inquiry/v1/findDoctorEvaluateList', {
                params: { doctorId, page, count: 5 }
            });

            if (res.data.status === '0000') {
                return {
                    data: res.data.result || [],
                    isRefresh
                };
            } else {
                return rejectWithValue(res.data.message || '获取评价列表失败');
            }
        } catch (error) {
            return rejectWithValue('获取评价列表失败，请稍后重试');
        }
    }
);

const evaluateSlice = createSlice({
    name: 'evaluate',
    initialState,
    reducers: {
        resetEvaluate: (state) => {
            state.list = [];
            state.page = 1;
            state.finished = false;
            state.error = null;
        },
        clearError: (state) => {
            state.error = null;
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchEvaluates.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(fetchEvaluates.fulfilled, (state, action) => {
                state.loading = false;
                if (action.payload.isRefresh) {
                    state.list = action.payload.data;
                } else {
                    state.list = [...state.list, ...action.payload.data];
                }
                state.finished = action.payload.data.length < 5;
                state.page = action.payload.isRefresh ? 1 : state.page + 1;
            })
            .addCase(fetchEvaluates.rejected, (state, action) => {
                state.loading = false;
                state.error = action.payload as string;
            });
    },
});

export const { resetEvaluate, clearError } = evaluateSlice.actions;
export default evaluateSlice.reducer; 